from datetime import datetime, timedelta
from django.db import transaction
from django.utils import timezone
from events.models import StoreProductReplenishment, StoreReplenishment
from product.models import ProductsInventory
from django.db.models import F

class StorageSimulatorService:
    def __init__(self, db_session=None):
        # Django ORM不需要显式的db_session
        pass

    def update_today_replenishment(self, date=None) -> None:
        """更新当天补货建议到库存"""
        # today = datetime.now().date()
        if date is None:
            date = timezone.localtime().date()
        today = date

        # 查询当天的补货建议，使用created_at而不是created_date
        replenishment_items = StoreProductReplenishment.objects.filter(
            created_at__date=today
        ).values('product_code', 'order_quantity')

        # 更新ProductsInventory表
        with transaction.atomic():
            for item in replenishment_items:
                ProductsInventory.objects.filter(
                    product_code=item['product_code']
                ).update(
                    delivery_quantity=F('delivery_quantity') + item['order_quantity']
                )

    def process_seven_days_ago_replenishment(self, date=None) -> None:
        """处理七天前的补货入库"""
        if date is None:
            date = timezone.localtime().date()
        seven_days_ago = date - timedelta(days=7)
        
        # 查询七天前的订单ID，使用created_at__date而不是created_date
        old_orders = StoreReplenishment.objects.filter(
            created_at__date=seven_days_ago
        ).values_list('order_id', flat=True)

        # 查询对应的补货建议明细
        replenishment_details = StoreProductReplenishment.objects.filter(
            order_id__in=old_orders
        ).values('product_code', 'order_quantity')

        # 更新库存
        with transaction.atomic():
            for detail in replenishment_details:
                ProductsInventory.objects.filter(
                    product_code=detail['product_code']
                ).update(
                    instock_quantity=F('instock_quantity') + detail['order_quantity'],
                    delivery_quantity=F('delivery_quantity') - detail['order_quantity']
                )
